<template>
  <!-- 个人信息编辑页 -->
  <div class="editUserInfo">
    <hmheader title="个人信息编辑">
      <!-- 插槽的使用 -->
      <span slot="left" class="iconfont iconjiantou2"></span>
      <span
        slot="right"
        class="van-icon van-icon-wap-home-o"
        style="font-size: 25px; color: red"
      ></span>
    </hmheader>
    <div class="userimg">
      <img :src="current.head_img" alt="" />
      <!-- 文件上传的组件 -->
      <van-uploader :after-read="afterRead" />
    </div>
    <hmcell
      title="昵称"
      :desc="current.nickname"
      @click="nickshow = !nickshow"
    ></hmcell>

    <van-dialog
      v-model="nickshow"
      title="编辑昵称"
      show-cancel-button
      @confirm="updateNickname"
      @cancel="editvalue.nickname = current.nickname"
    >
      <van-field
        v-model="editvalue.nickname"
        required
        label="昵称"
        placeholder="请输入昵称"
      >
      </van-field>
    </van-dialog>

    <hmcell title="密码" desc="******" @click="passshow = !passshow"></hmcell>
    <van-dialog
      title="修改密码"
      v-model="passshow"
      @cancel="editvalue.originpass = editvalue.newpass = ''"
      @confirm='updatePass'
      :before-close="beforeClose"
      show-cancel-button
    >
      <van-field
        placeholder="请输入原密码"
        required
        label="原密码"
        v-model="editvalue.originpass"
      ></van-field>
      <van-field
        placeholder="请输入新密码"
        required
        label="新密码"
        v-model="editvalue.newpass"
      ></van-field>
    </van-dialog>
    <!-- 修改昵称 -->
    <hmcell title="性别" :desc="current.gender == 1 ? '男' : '女'" @click="gendershow = !gendershow"></hmcell>
    <van-dialog v-model="gendershow" title="修改性别" 
                show-cancel-button
                @confirm='updateGender'
                @cancel='editvalue.gender= current.gender'>
                <!-- 系统的是先女后男 所以这个索引值也得先女后男 -->
      <van-picker :columns="['女','男']"
                  :default-index="current.gender"
                  @change="genderChange"></van-picker>
    </van-dialog>
  </div>
</template>
<script>
import hmheader from "@/components/hmheader.vue";
import hmcell from "@/components/hmcell.vue";
import { uploadFile } from "@/apis/upload.js";
import { getUserInfo, updateUserInfo } from "@/apis/user.js";
import axios from "@/utils/myaxios.js";
export default {
  data() {
    return {
      current: {},
       editvalue:{   
        // 规范命名   中文意思转英文
        originpass:'',
        newpass:''
      },
      nickshow: false,
      passshow:false,
      gendershow:false
    };
  },
  components: {
    hmheader,
    hmcell,
  },
  methods: {
    async afterRead(myfile) {
      // 此时可以自行将文件上传至服务器
      // console.log(file);
      // console.log(myfile.file)
      console.log(this.current);
      // 收集文件数据
      let formdata = new FormData();
      formdata.append("file", myfile.file);
      // 实现文件上传
      let res = await uploadFile(formdata);
      this.current.head_img = axios.defaults.baseURL + res.data.data.url;
      console.log(res);
      if (res.data.message == "文件上传成功") {
        // 2.编辑用户头像
        let res2 = await updateUserInfo(this.current.id, {
          head_img: res.data.data.url,
        });
        this.$toast.success("用户头像修改成功");
        console.log(res2);
      }
    },
    // 编辑昵称
    async updateNickname() {
      let res = await updateUserInfo(this.current.id, {
        nickname: this.editvalue.nickname,
      });
      this.current.nickname = this.editvalue.nickname;
      this.$toast.success("用户昵称修改成功");
      console.log(res);
    },
    // 修改密码——先获取到原密码——原密码匹配验证——修改密码（一般用正则表达式规则修改）
    async updatePass (){
      let userobj = JSON.parse(localStorage.getItem('toutiao_59_userinfo'))
      // 判断原密码是否匹配正确
      if(this.editvalue.originpass == userobj.password){
        // 新密码的验证
        if(/^.{3,}$/.test(this.editvalue.newpass)){
          let res = await updateUserInfo(this.current.id,{password:this.editvalue.newpass})
          console.log(res);
          this.$toast.success('用户密码修改成功')
          // 更新数据
          userobj.password= this.editvalue.newpass
          // 重新存储
          localStorage.setItem('toutiao_59_userinfo',JSON.stringify(userobj))
          // 清空
          this.editvalue.originpass = this.editvalue.newpass = ''
        }else{
          this.$toast.fail('新密码输入不正确')
        }
      }else{
          this.$toast.fail('原密码输入不正确')
        }
    },
      // 添加用户体验，阻止模态框的关闭
    beforeClose (action,done) {
      // 点击确认
      if (action == 'confirm') {
        let userobj = JSON.parse(localStorage.getItem('toutiao_59_userinfo'))
        // 判断 原密码是否匹配
        if (this.editvalue.originpass != userobj.password) {
          done(false)
        } else {
          if (!/^.{3,}$/.test(this.editvalue.newpass)) {
            done(false)
          } else {
            done()
          }
        }
      }  else { // 点击取消
        done()
        }
    },
    // 修改性别
  async updateGender (){
    let res = await updateUserInfo(this.current.id,{gender:this.editvalue.gender})
    console.log(res);
    this.current.gender = this.editvalue.gender
    this.$toast.success('用户性别修改成功')
  },
  genderChange (q,qq,index){
    this.editvalue.gender = index
  },
  },
  


  async mounted() {
    let res = await getUserInfo(this.$route.params.id);
    console.log(res);
    if (res.data.message == "获取成功") {
      res.data.data.head_img = axios.defaults.baseURL + res.data.data.head_img;
      this.current = res.data.data;
      // 仅仅是方便我们编辑时的数据展示和数据获取
      this.editvalue = { ...this.current }
      this.editvalue.nickname = this.current.nickname
      console.log(this.editvalue);
    }
  },
}
</script>
<style lang="less" scoped>
.userimg {
  padding: 30px 0;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  img {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    border: 1px solid red;
  }
  /deep/.van-uploader {
    position: absolute;
    left: 51%;
    top: 52%;
    transform: translate(-50%, -50%);
    opacity: 0;
  }
  /deep/.van-uploader__upload {
    width: 100px;
    height: 100px;
    margin: 0;
  }
}
</style>